﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebAPITest.Models.Database;

namespace WebAPITest.service
{
    public class UserService : IUserService
    {
        private readonly StackExchange.Redis.IDatabase _redis;
        private readonly WebEnterpriseIIContext _db;
        /// <summary>
        /// 用户服务
        /// </summary>
        /// <param name="db"></param>
        public UserService(WebEnterpriseIIContext db, RedisHelper client)
        {
            _db = db;
            _redis = client.GetDatabase();
        }


        /// <summary>
        /// 根据用户名获取用户对象
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public User GetUserByUserName(string userName)
        {
            return _db.Users.FirstOrDefault(x => x.UserName == userName);
        }
        /// <summary>
        /// 添加用户/用户注册
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="salt"></param>
        /// <param name="nickname"></param>
        /// <param name="userlevel"></param>
        /// <param name="email"></param>
        /// <param name="createtime"></param>
        /// <returns></returns>
        public User AddUser(string username, string password, byte salt, string nickname, int userlevel, string email, string createtime = null)
        {

            User user = new Models.Database.User();
            user.UserName = username;
            user.Password = password;
            user.Salt = salt;
            user.Email = email;
            user.NickName = nickname;
            user.UserLevel = (byte)userlevel;
            return user;
        }
        /// <summary>
        /// 通过商品编号搜索商品信息
        /// </summary>
        /// <param name="goodid"></param>
        /// <returns></returns>
        public Good GetGoodByGoodId(int goodid)
        {
            return _db.Goods.FirstOrDefault(x => x.Id == goodid);
        }
        
        /// <summary>
        /// 查看之前浏览的记录
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public List<Good> selectUserHistory(string userid)
        {
            return JsonConvert.DeserializeObject<List<Good>>(_redis.StringGet(userid));
        }
        

        public List<Good> AddUserHistory(List<Good> record,Good good,string userid)
        {
            var views = new List<Good>();
            views.Add(good);
            if (record != null) {
                views.AddRange(record);
            }
            var jsonStr = JsonConvert.SerializeObject(views);
            _redis.StringSet(userid, jsonStr);
            return views;
        }
    }
}
